<template>
  <div class="component-manage-container">
    <div class="header">
      <h2>组件管理</h2>
      <el-button type="primary" @click="openAddComponentDialog">添加组件</el-button>
    </div>

    <el-table
      :data="componentList"
      style="width: 100%"
      v-loading="loading"
    >
      <!-- <el-table-column prop="id" label="ID" width="80"></el-table-column> -->
      <el-table-column prop="name" label="组件名称"></el-table-column>
      <el-table-column prop="category" label="分类"></el-table-column>
      <el-table-column prop="tags" label="标签"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            size="small"
            @click="openEditComponentDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDeleteComponent(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="fetchComponentList"
      @current-change="fetchComponentList"
    />

    <el-dialog
      :title="dialogMode === 'add' ? '添加组件' : '编辑组件'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="currentComponent"
        label-width="100px"
        :rules="componentRules"
        ref="componentFormRef"
      >
        <el-form-item label="组件名称" prop="name">
          <el-input v-model="currentComponent.name"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="currentComponent.category"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="currentComponent.tags"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="currentComponent.description"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSaveComponent"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import {
    addComponent,
    deleteComponent,
    fetchAllComponents,
    updateComponent
} from '../services/api'

// 分页和列表
const componentList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentComponent = ref({
  id: null,
  name: '',
  category: '',
  tags: '',
  description: ''
})

const componentFormRef = ref(null)

// 表单验证规则
const componentRules = {
  name: [
    { required: true, message: '请输入组件名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入组件分类', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请输入组件标签', trigger: 'blur' }
  ]
}

// 获取组件列表
const fetchComponentList = async () => {
  loading.value = true
  try {
    const response = await fetchAllComponents(currentPage.value, pageSize.value)
    // 确保 componentList 是数组
    componentList.value = Array.isArray(response.data.data) ? response.data.data : []
    total.value = componentList.value.length
  } catch (error) {
    ElMessage.error('获取组件列表失败')
    console.error(error)
    componentList.value = []  // 出错时设置为空数组
  } finally {
    loading.value = false
  }
}

// 打开添加组件对话框
const openAddComponentDialog = () => {
  dialogMode.value = 'add'
  currentComponent.value = {
    id: null,
    name: '',
    category: '',
    tags: '',
    description: ''
  }
  dialogVisible.value = true
}

// 打开编辑组件对话框
const openEditComponentDialog = (component) => {
  dialogMode.value = 'edit'
  currentComponent.value = { ...component }
  dialogVisible.value = true
}

// 保存组件（添加或编辑）
const handleSaveComponent = async () => {
  const formRef = componentFormRef.value
  if (!formRef) return

  await formRef.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogMode.value === 'add') {
          await addComponent(currentComponent.value)
          ElMessage.success('添加组件成功')
        } else {
          await updateComponent(currentComponent.value)
          ElMessage.success('更新组件成功')
        }
        dialogVisible.value = false
        fetchComponentList()
      } catch (error) {
        ElMessage.error(dialogMode.value === 'add' ? '添加组件失败' : '更新组件失败')
      }
    }
  })
}

// 删除组件
const handleDeleteComponent = (component) => {
  ElMessageBox.confirm(
    `确定要删除组件 "${component.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteComponent(component.id)
      ElMessage.success('删除组件成功')
      fetchComponentList()
    } catch (error) {
      ElMessage.error('删除组件失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 页面加载时获取组件列表
onMounted(() => {
  fetchComponentList()
})
</script>

<style scoped>
.component-manage-container {
  background-color: #111827;
  border-radius: 8px;
  padding: 20px;
  color: #f3f4f6;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-table {
  --el-table-bg-color: #1f2937;
  --el-table-header-bg-color: #374151;
  --el-table-tr-bg-color: #1f2937;
  --el-table-row-hover-bg-color: #374151;
  --el-table-text-color: #f3f4f6;
  --el-table-header-text-color: #ffffff;
  --el-border-color-lighter: rgba(255,255,255,0.1);

  background-color: var(--el-table-bg-color);
  color: var(--el-table-text-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.el-table th {
  background-color: var(--el-table-header-bg-color) !important;
  color: var(--el-table-header-text-color);
  font-weight: 600;
}

.el-table tr {
  background-color: var(--el-table-tr-bg-color) !important;
  color: var(--el-table-text-color);
}

/* 强制所有行保持一致 */
.el-table .el-table__body tr {
  background-color: #1f2937 !important;
}

/* 修复偶数行样式问题 */
.el-table--striped .el-table__body tr.el-table__row--striped td,
.el-table .el-table__body tr.el-table__row--striped,
.el-table .el-table__body tr.el-table__row--striped.hover-row {
  background-color: #1f2937 !important;
}

/* 确保内部单元格也有正确的背景色 */
.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background-color: #1f2937 !important;
}

/* 重置Element UI的斑马纹效果 */
.el-table--enable-row-hover .el-table__body tr:hover td.el-table__cell {
  background-color: var(--el-table-row-hover-bg-color) !important;
}

.el-table tr:hover {
  background-color: var(--el-table-row-hover-bg-color) !important;
}

.el-table__cell {
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  color: #f3f4f6;
}

.el-button--primary {
  background-color: #3450ff;
  border-color: #3450ff;
}

.el-button--primary:hover {
  background-color: #2440db;
  border-color: #2440db;
}

/* 调整分页器样式 */
.el-pagination .el-pager li {
  background-color: #1f2937;
  color: #f3f4f6;
}

.el-pagination .el-pager li:hover {
  color: #3450ff;
}

.el-pagination .el-pager li.is-active {
  background-color: #3450ff;
  color: white;
}
</style>
